import { DownOutlined } from '@ant-design/icons';
import { Button, Dropdown, Input, Layout, Menu, message } from 'antd';
import axios, { CancelTokenSource } from 'axios';
import { useEffect, useRef, useState } from 'react';
import AppMarket from './AppMarket';
import './ApplicationFunc.scss';
import './CustomerLoading.scss';

const { Search } = Input;
const { Content, Footer } = Layout;

interface Tag {
  tagId: string;
  tagName: string;
}

interface App {
  flowId: string;
  flowName: string;
  userName: string;
  description: string;
  downloadCount: number;
  likeCount: number;
  likedByUser: boolean;
  tags: Tag[];
}

const initialTags: Tag[] = [
  { tagId: 'default-official', tagName: '官方' }
];

const sortOptions = [
  { key: 'download_count', label: '最热' }
];

const filterOptions = [
  { key: 'all', label: '全部' },
  { key: 'favorites', label: '喜欢' }
];

const CustomLoader: React.FC = () => {
  return (
    <div className="custom-loader">
      <div className="loader-circle">
        <div className="loader-inner"></div>
      </div>
      <div className="loader-text">加载中...</div>
    </div>
  );
};

const ApplicationFunc: React.FC = () => {
  const [tags, setTags] = useState<Tag[]>(initialTags);
  const [selectedCategory, setSelectedCategory] = useState<string>('官方');
  const [sort, setSort] = useState<string>('download_count');
  const [filter, setFilter] = useState<string>('all');
  const [search, setSearch] = useState<string>('');
  const [apps, setApps] = useState<App[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [page, setPage] = useState<number>(1);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const limit = 6;

  const cancelTokenSource = useRef<CancelTokenSource>();

  useEffect(() => {
    const fetchTags = async () => {
      try {
        const response = await axios.get('http://localhost:8080/store/tags');
        if (response.data.code === 1 && response.data.message === "Success") {
          setTags(prevTags => [...prevTags, ...response.data.data.tags]);
          console.log("Fetched tags:", response.data.data.tags);
        } else {
          message.error('Failed to fetch tags');
        }
      } catch (error) {
        console.error('Error fetching tags:', error);
        message.error('Error fetching tags');
      }
    };

    fetchTags();
  }, []);

  const fetchApps = async (reset: boolean = false) => {
    // 取消上一个请求
    if (cancelTokenSource.current) {
      cancelTokenSource.current.cancel('Operation canceled due to new request.');
    }

    // 为新的请求创建一个取消令牌
    cancelTokenSource.current = axios.CancelToken.source();

    console.log(`Fetching apps, page: ${reset ? 1 : page}, reset: ${reset}`);
    console.log(`Request params - userId: '2e56ea15-5853-46a7-a5f5-f0346d28a2a9', tags: ${selectedCategory === '官方' ? 'undefined' : selectedCategory}, sort: ${sort}, page: ${reset ? 1 : page}, limit: ${limit}, likedByUser: ${filter === 'favorites'}, search: ${search}`);
    setLoading(true);

    try {
      const response = await axios.get('http://localhost:8080/store/components/query', {
        cancelToken: cancelTokenSource.current.token,
        params: {
          userId: '2e56ea15-5853-46a7-a5f5-f0346d28a2a9',
          tags: selectedCategory === '官方' ? undefined : selectedCategory,
          sort,
          page: reset ? 1 : page,
          limit,
          likedByUser: filter === 'favorites',
          search: search ? search : undefined
        }
      });
      console.log("Response:", response);
      if (response.data.code === 1 && response.data.message === "Success") {
        const newApps = response.data.data.results;
        console.log("Fetched apps:", newApps);
        setApps(reset ? newApps : [...apps, ...newApps]);
        if (newApps.length === limit) {
          setPage(prevPage => prevPage + 1); // 如果返回的数据数量等于limit，增加page
        } else {
          setHasMore(false); // 如果返回的数据数量少于limit，不再继续加载
        }
      } else {
        message.error('Failed to fetch apps');
      }
    } catch (error) {
      if (axios.isCancel(error)) {
        console.log('Request canceled:', error.message);
      } else {
        console.error('Error fetching apps:', error);
        message.error('Error fetching apps');
      }
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchApps(true);
    // 在组件卸载时取消未完成的请求
    return () => {
      if (cancelTokenSource.current) {
        cancelTokenSource.current.cancel('Component unmounted.');
      }
    };
  }, [selectedCategory, sort, filter, search]);

  useEffect(() => {
    if (page > 1 && hasMore) {
      fetchApps();
    }
  }, [page]);

  const handleCategoryClick = (category: string) => {
    console.log("Selected category:", category);
    setSelectedCategory(category);
    setPage(1);
    setHasMore(true); // 重置加载更多的状态
    setLoading(true);
  };

  const handleSortChange = ({ key }: any) => {
    console.log("Selected sort:", key);
    setSort(key);
    setPage(1);
    setHasMore(true); // 重置加载更多的状态
    setLoading(true);
  };

  const handleFilterChange = ({ key }: any) => {
    console.log("Selected filter:", key);
    setFilter(key);
    setPage(1);
    setHasMore(true); // 重置加载更多的状态
    setLoading(true);
  };

  const handleSearch = (value: string) => {
    console.log("Search term:", value);
    setSearch(value);
    setPage(1);
    setHasMore(true); // 重置加载更多的状态
    setLoading(true);
  };

  const sortMenu = (
    <Menu onClick={handleSortChange}>
      {sortOptions.map(option => (
        <Menu.Item key={option.key}>
          {option.label}
        </Menu.Item>
      ))}
    </Menu>
  );

  const filterMenu = (
    <Menu onClick={handleFilterChange}>
      {filterOptions.map(option => (
        <Menu.Item key={option.key}>
          {option.label}
        </Menu.Item>
      ))}
    </Menu>
  );

  const tagMenu = (
    <Menu>
      {tags.slice(8).map((tag) => (
        <Menu.Item key={tag.tagId} onClick={() => handleCategoryClick(tag.tagName)}>
          {tag.tagName}
        </Menu.Item>
      ))}
    </Menu>
  );

  if (loading && page === 1) {
    return (
      <div className="custom-loader-wrapper">
        <CustomLoader />
      </div>
    );
  }

  return (
    <Layout className="main-layout">  
      <Content className="dynamic-content">
        <div className="data-market">
          <div className='top-menu'>
            <h1>应用广场</h1>
            <div className="search-bar">
              <Dropdown overlay={sortMenu}>
                <p style={{ margin: '0 0', cursor: 'pointer' }}>排序：{sortOptions.find(option => option.key === sort)?.label} <DownOutlined /></p>
              </Dropdown>
              <Dropdown overlay={filterMenu}>
                <p style={{ margin: '0 1.25rem', cursor: 'pointer' }}>筛选：{filterOptions.find(option => option.key === filter)?.label} <DownOutlined /></p>
              </Dropdown>
              <Search
                placeholder="搜索数据集"
                style={{ width: 240 }}
                onSearch={handleSearch}
              />
              <Button type="primary" className='start-chat-button'>创建数据集</Button>
            </div>
          </div>
          <div className="category-menu">
            {tags.slice(0, 8).map((tag) => (
              <Button
                key={tag.tagId}
                type={selectedCategory === tag.tagName ? 'primary' : 'default'}
                style={{ borderColor: 'white', borderRadius: '0rem' }}
                className='yingyong-tagbutton'
                onClick={() => handleCategoryClick(tag.tagName)}>
                {tag.tagName}
              </Button>
            ))}
            <Dropdown overlay={tagMenu}>
              <Button style={{ borderColor: 'white', borderRadius: '0rem' }}>
                更多 <DownOutlined />
              </Button>
            </Dropdown>
          </div>
        </div>
      </Content>
      <Footer className="scrollable-footer">
        <div className="data-list">
          <AppMarket apps={apps} loadMoreApps={() => setPage(page + 1)} />
        </div>
      </Footer>
    </Layout>
  );
};

export default ApplicationFunc;
